﻿using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows;

namespace VS.Infrastructure.Converters
{
    public class StaticResourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                var uri = (string)value;

                Stream xaml = this.GetType().Assembly.GetManifestResourceStream(uri);
                using (StreamReader tr = new StreamReader(xaml))
                {
                    object o = XamlReader.Load(tr.ReadToEnd());


                    FrameworkElement fe = o as FrameworkElement;
                    if (fe != null) fe.DataContext = parameter;
                    return o;
                }
            }
            catch (Exception e)
            {
                return string.Format("Error : {0}", e.Message);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}
